package com.example.hfweather.ui.me

import android.annotation.SuppressLint
import android.app.Activity
import android.app.AlertDialog
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Bundle
import android.provider.MediaStore
import android.util.Log
import android.view.LayoutInflater
import android.widget.Toast
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.core.content.FileProvider
import androidx.lifecycle.lifecycleScope
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.example.hfweather.R
import com.example.hfweather.WeatherApplication

import com.example.hfweather.base.BaseBindingActivity
import com.example.hfweather.databinding.ActChangeAvatarBinding
import com.example.hfweather.storage.TokenPreferences
import com.example.hfweather.util.AvatarUploader
import kotlinx.coroutines.launch
import java.io.File
import java.io.FileOutputStream
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
import java.util.jar.Manifest

class ChangeAvatarActivity : BaseBindingActivity<ActChangeAvatarBinding>() {

    private val REQUEST_IMAGE_CAPTURE = 1//拍照请求码
    private val REQUEST_IMAGE_PICK = 2//相册请求码
    // 新增专用权限请求码
    private val REQUEST_CAMERA_PERMISSION = 100

    private lateinit var tempPhotoFile: File

    //头像地址
    var avatarUrl: String? = null


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        //从全局中获取头像地址
        avatarUrl = WeatherApplication.user?.avatar
        //头像
        loadAvatar(avatarUrl,this)

        setOnClickEvent()
    }
    override fun onDestroy() {
        if (::tempPhotoFile.isInitialized && tempPhotoFile.exists()) {
            tempPhotoFile.delete()
        }
        super.onDestroy()
    }

    override fun initBinding(layoutInflater: LayoutInflater): ActChangeAvatarBinding {
        return ActChangeAvatarBinding.inflate(layoutInflater)
    }

    private fun setOnClickEvent() {
        //1. 返回
        binding.ivBack.setOnClickListener {
            finish()
        }
        //2. 选择头像
        binding.ivAvatar.setOnClickListener {
            showSelectAvatarDialog()
        }
        binding.ivEditAvatar.setOnClickListener {
            showSelectAvatarDialog()
        }
    }

    /**
     * 显示选择头像的弹层
     */
    private fun showSelectAvatarDialog() {
        //创建alert弹层提示拍照或从相册选择获取头像
        val alertDialog = AlertDialog.Builder(this)
            .setTitle("选择头像")
            .setItems(arrayOf("拍照", "相册","取消")) { dialog, which ->
                when (which) {
                    0 -> {
                        //拍照
                        takePhoto()
                    }
                    1 -> {
                        //从相册选择
                        openAlbum()
                    }
                    2 -> {
                        //取消
                        dialog.dismiss()
                    }
                }
            }
            .create()
            .show()
    }

    /**
     * 拍照
     */

    private fun takePhoto() {
        val permission = android.Manifest.permission.CAMERA
        if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, arrayOf(permission), REQUEST_CAMERA_PERMISSION)
        }

        else {
            launchCamera()
        }
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == REQUEST_CAMERA_PERMISSION && grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            launchCamera()
        } else {
            Toast.makeText(this, "相机权限被拒绝", Toast.LENGTH_SHORT).show()
        }
    }
    private fun launchCamera() {
        // 检查设备是否有相机
        if (packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA_ANY)) {
            val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
            // ...后续逻辑
//            val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
            tempPhotoFile = createTempImageFile() // 创建临时文件
            val photoUri = FileProvider.getUriForFile(
                this,
                "${applicationContext.packageName}.fileprovider",
                tempPhotoFile
            )
            intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri)
            startActivityForResult(intent, REQUEST_IMAGE_CAPTURE)
        } else {
            Toast.makeText(this, "设备无可用相机", Toast.LENGTH_SHORT).show()
        }
    }

    private fun createTempImageFile(): File {
        val timestamp = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(Date())

        return File.createTempFile("avatar_${timestamp}", ".jpg", externalCacheDir)
    }
    /**
     * 从相册选择
     */
    @SuppressLint("IntentReset")
    private fun openAlbum() {
        //创建一个意图，打开相册选择图片
        //让图片来源来自外部存储的图片媒体
        val intent = Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
        //2.约束图片类型
        intent.type = "image/*"
        //3.启动意图
        startActivityForResult(intent, REQUEST_IMAGE_PICK)

    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        when(requestCode) {
            REQUEST_IMAGE_CAPTURE -> {
                if (resultCode == Activity.RESULT_OK) {
                    uploadAvatar(Uri.fromFile(tempPhotoFile)) // 使用临时文件Uri
                }
            }
            REQUEST_IMAGE_PICK -> {
                if (resultCode == Activity.RESULT_OK) {
                    //获取图片的uri
                    data?.data?.let {uri ->
                        //上传 图片
                        uploadAvatar(uri)
                        //加载图片
//                    loadAvatar(imageUri.toString(), this)
                    }

                }
            }

        }
    }

    /**
     * 上传头像
     */
    private fun uploadAvatar(uri: Uri ) {
        //获取token
        val token = TokenPreferences.getInstance(this).getToken()
        //1.开启协程
        lifecycleScope.launch {
            AvatarUploader(this@ChangeAvatarActivity, token.toString()){url, error ->
                if (error!=null){
                    Toast.makeText(this@ChangeAvatarActivity, "${error}上传头像失败", Toast.LENGTH_SHORT).show()
                }else{
//                    Toast.makeText(this@ChangeAvatarActivity, "上传头像成功", Toast.LENGTH_SHORT).show()
                    loadAvatar(url.toString(), this@ChangeAvatarActivity)
                }
            }.uploadAvatar(uri)
        }

    }
    /**
     * 加载头像
     */

    private fun loadAvatar(url: String?, context: Context) {
        lifecycleScope.launch {
            Glide.with(context)
                .load(url)
                .apply(
                    RequestOptions()
                        .placeholder(R.mipmap.avatar1)
                        .error(R.mipmap.avatar1))
                .into(binding.ivAvatar)
        }
    }
}